package pres.liko.iot.gateway.filters;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import pres.liko.iot.gateway.config.ApisCacheConfig;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Set;

/**
 * @ClassName: BlackIpGlobalFilter
 * @Auther: liko
 * @Description: api黑名单
 * @Date: 2022/11/1 22:50
 */
@Component
public class BlackApiGlobalFilter implements Ordered, GlobalFilter {

    private ApisCacheConfig apisCacheConfig;

    @Autowired
    public BlackApiGlobalFilter(ApisCacheConfig apisCacheConfig) {
        this.apisCacheConfig = apisCacheConfig;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 获取到所有的api黑名单
        Set<String> apis = apisCacheConfig.getBlackcache();
        // 获取api
        // String uri = exchange.getRequest().getURI().getPath();

        String uri = exchange.getRequest().getPath().toString();

        // 判断是否在黑名单中
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        // return Mono.just(apis.stream().noneMatch(s -> antPathMatcher.match(s, uri)))
        //         .filter(aBoolean -> aBoolean)
        //         // 根据结果来决定是否放行
        //         .map(strings -> chain.filter(exchange))// 不在黑名单的人放行
        //         .defaultIfEmpty(
        //                 exchange.getResponse().writeAndFlushWith(
        //                         Mono.just(
        //                                 Mono.just(
        //                                         DefaultDataBufferFactory
        //                                                 .sharedInstance
        //                                                 .allocateBuffer()
        //                                                 .write("非法请求".getBytes(StandardCharsets.UTF_8))
        //                                 )
        //                         )
        //                 )
        //         ).flatMap(voidMono -> voidMono);//拦截，返回一个提示
        return Mono.just(apis.stream().anyMatch(partten -> antPathMatcher.match(partten, uri)))
                .filter(b -> b)
                .map(s -> exchange.getResponse().writeAndFlushWith( //返回默认的提示信息
                        Mono.just(Mono.just(DefaultDataBufferFactory.sharedInstance
                                .allocateBuffer().write("网络异常,请检查您的网络".getBytes(StandardCharsets.UTF_8))
                        ))))
                .defaultIfEmpty(chain.filter(exchange))
                .flatMap(result -> result);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
